#!/usr/bin/env node

const http = require('https');
const log =console.log;
const cheerio = require('cheerio');
const baseURL = 'https://ke.segmentfault.com';


function getHTMLPage() {
    return new Promise(resolve => {
        http.get(`${baseURL}/free`, res => {
            let html = '';
            res.on('data', chunk=> html += chunk);
            res.on('end', ()=> resolve(html));
        })
    })
} 

function getCourseInfo (html){
    let $ = cheerio.load(html);
    $('body')
        .find('a.text-reset.stretched-link')
        .each(function() {
            const cName = $(this).text(),
                  cURL = baseURL + $(this).attr('href');
            log('course name:', cName);
            log('course URL:', cURL);
            log();
        });
}

async function main() {
    const html = await getHTMLPage();
    getCourseInfo(html);
}

main();